package com.yr.manager.controller;

import com.yr.manager.client.userclient;
import com.yr.manager.pojo.user;
import com.yr.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/rest")
public class controller {
    @Autowired
    private RestTemplate restTemplate;
    private static final String USER_SERVICE = "user";

    @Autowired
    LoadBalancerClient loadBalancerClient;      // 引入负载均衡组件
    @Autowired
    private userclient userClient;

    //1. 查询所有用户列表 (restTemplate来调用远程服务)
    @GetMapping("/user/list")
    public R listUser(){
        ServiceInstance instance = loadBalancerClient.choose(USER_SERVICE);
        ResponseEntity<R> exchange = restTemplate.exchange(instance.getUri() + "/user/list", HttpMethod.GET, null, R.class);
        return exchange.getBody();
    }

    @GetMapping("/user/selectById1")
    public R selectById1(){
        ServiceInstance instance = loadBalancerClient.choose("user");
        user user = restTemplate.getForObject(instance.getUri() + "/user/selectById", user.class);
        return R.success();
    }

    //3. 查询单个用户(openFeign调用实现)
    @GetMapping("/user/selectById2")
    public R selectById2(){
        return R.success(userClient.selectById1());
    }

}
